<template>
  <el-row class="container mx-auto">
    <el-col class="flex justify-center mt-6">
      <h1 class="text-4xl font-bold tracking-tight">纪委书记邮箱</h1>
    </el-col>
    <el-col class="mt-10">
      <el-form
        ref="formRef"
        :rules="formRules"
        :model="formData"
        status-icon
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入标题"
            maxlength="90"
            minlength="4"
            show-word-limit="true"
            required="true"
          />
        </el-form-item>
        <el-form-item label="留言">
          <Editor v-model="formData.content" height="400px" />
        </el-form-item>
        <el-form-item class="flex justify-center">
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import * as MailboxApi from '@/api/mailbox'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push } = useRouter()

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  title: undefined,
  mailboxCategory: 1,
  content: '',
  isNoted: 0,
  attFileName: undefined
})
const formRules = reactive({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '留言内容不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MailboxApi.MailboxVO
    await MailboxApi.createMailbox(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    resetForm()
    await push('/online/mailbox/jiwei')
  } finally {
    formLoading.value = false
  }
}
const resetForm = () => {
  formData.value = {
    title: undefined,
    mailboxCategory: undefined,
    contactNumber: undefined,
    content: undefined,
    attFileName: undefined
  }
  formRef.value?.resetFields()
}
</script>
